<template>
  <div class="context">
    <mavon-editor
        ref="md"
        v-model="form.content"
        :ishljs="true"
        style="min-height: 600px"
        @imgAdd="imgAdd"
        @save="saveStatusToFalse"
    >
      <template #left-toolbar-after>
<!--        <button-->
<!--            type="button"-->
<!--            title="发表"-->
<!--            class="op-icon fa markdown-upload iconfont iconupload"-->
<!--            aria-hidden="true"-->
<!--            @click="formVisible = true;"-->
<!--        >-->
<!--          <el-icon>-->
<!--            <UploadFilled/>-->
<!--          </el-icon>-->
<!--        </button>-->

        <button
            type="button"
            title="草稿箱"
            class="op-icon fa markdown-upload iconfont iconupload"
            aria-hidden="true"
            @click="showDialogFormVisible"
        >
          <el-icon>
            <TakeawayBox/>
          </el-icon>
        </button>
      </template>
    </mavon-editor>
  </div>

  <!--  草稿箱-->
  <el-dialog v-model="dialogFormVisible" title="草稿箱" width="800" draggable>
    <el-empty description="没有数据" v-if="drafts.length == 0"/>
    <el-card v-for="(item,idx) in drafts" style="margin-bottom: 20px" v-else @click.="showArticle(item)">
      <el-form label-width="100px">
        <!-- 文章标题 -->
        <el-form-item label="标题">
          <span>{{ item.title }}</span>
        </el-form-item>

        <!-- 描述 -->
        <el-form-item label="描述">
          <span>{{ item.description }}</span>
        </el-form-item>

      </el-form>
      <el-button type="danger" @click.stop="deleteDraftsByUUID(item)" style="margin-left: 8%">
        删除
      </el-button>
    </el-card>
    <div>
      <el-pagination small
                     layout="prev, pager, next"
                     :total="pages.draftsPage"
                     :default-page-size="2"
                     @current-change="draftsHandleCurrentChange"
      />
    </div>
  </el-dialog>

  <!--  文章-->
  <el-dialog v-model="formVisible" title="详细信息" width="800" draggable>
    <el-form label-width="100px">
      <!-- 文章标题 -->
      <el-form-item label="标题">
        <el-input v-model="form.title" placeholder="请输入标题"/>
      </el-form-item>

      <!-- 简述 -->
      <el-form-item label="简述">
        <el-input v-model="form.description" placeholder="用一句话描述你的文章"/>
      </el-form-item>

      <!-- 展示图 -->
      <el-form-item label="展示图">
        <div>
          <el-upload class="avatar-uploader"
                     method="post" action="http://localhost:8080/files/upload"
                     :show-file-list="false"
                     :headers="{'token' : token}"
                     :on-success="        (response, file, fileList) => {
          return uploadSuccess(response);
        }">
            <img v-if="form.showPhoto" :src="form.showPhoto" class="avatar" alt="网络错误"
                 style="width: 200px;height: 200px"/>
            <el-icon v-else class="avatar-uploader-icon" :size="80" color="#79bbff">
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
      </el-form-item>

      <!-- 是否发表的滑块 -->
      <el-form-item label="是否发表">
        <el-switch v-model="form.status" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitEditor">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import axios from 'axios';
import {ref} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";
import {Plus} from "@element-plus/icons-vue";


const dialogFormVisible = ref(false)
const router = useRouter()
const md = ref()
const formVisible = ref(false)

const token = localStorage.getItem('token');

// 编辑数据
const form = ref({
  uuid: "",
  title: "",
  content: "",
  description: "",
  showPhoto: "",
  status: false,
  html:"",
})

// 草稿箱数据
const drafts = ref([])

// 分页数据
const pages = ref({
  //草稿箱
  draftsPage: 0,
})

// 图片上传
const imgAdd = (pos, $file) => {
  const file = new FormData();
  file.append("file", $file);
  //将下面上传接口替换为你自己的服务器接口
  axios.post("/files/upload", file).then(res => {
    // console.log(res)
    md.value.$img2Url(pos, "http://localhost:8080/files/shows/" + res.message)
  })
}


// 编辑
const submitEditor = () => {
  // 发表
  if (form.value.status) {
    axios.post("writes/editor", form.value).then(res => {
      ElMessage({
        message: res.message,
        type: 'success',
        duration: 3000
      })
      localStorage.setItem("navbarIndex","0")
      setTimeout(function () {
        router.replace("/index/home/75395123")
      }, 1000)
    })
  } else {
    // 保存
    axios.post("writes/editor", form.value).then(res => {
      if (res["data"]) {
        form.value.uuid = res.data.uuid;
      }
      ElMessage({
        message: res.message,
        type: 'success',
        duration: 3000
      })

      setTimeout(function () {
        formVisible.value = false;
      }, 1000)
    })
  }
}

const uploadSuccess = (response) => {
  // console.log(response)
  form.value.showPhoto = "http://localhost:8080/files/shows/" + response.message
}

const showDialogFormVisible = () => {
  dialogFormVisible.value = true
  drafts.value = [];
  draftsPages(1, 2);
}

//草稿箱分页
const draftsPages = (start, page) => {
  axios.get("writes/userId", {
    params: {
      start: Number(start),
      pages: Number(page),
    }
  }).then(res => {
    console.log("草稿箱分页", res)
    drafts.value = res.data
    pages.value.draftsPage = res.data[drafts.value.length - 1].total;
    drafts.value.splice(drafts.value.length - 1, 1)
  })
}


//将当前文章换成点击的文章
const showArticle = (item) => {
  axios.get("writes/" + item.uuid).then(res => {
    console.log(res)
    const draft = res.data;
    form.value.uuid = draft.uuid;
    form.value.title = draft.title;
    form.value.content = draft.content;
    form.value.description = draft.description;
    form.value.showPhoto = "http://localhost:8080/files/shows/" + draft.show_photo;
    form.value.status = draft.status !== 0;
    setTimeout(function () {
      dialogFormVisible.value = false;
    }, 500)
  })
}

const draftsHandleCurrentChange = (number) => {
  // console.log("你好",number)
  draftsPages(number, 2)
}

// 删除文章
const deleteDraftsByUUID = (item) => {
  ElMessageBox.confirm(
      '请确认是否删除', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        distinguishCancelAndClose: true,
        callback: (action) => {
          // console.log(action)
          if (action === "confirm") {
            axios.delete("writes/" + item.uuid).then(res => {
              ElMessage({
                message: res.message,
                type: 'success',
                duration: 3000
              })
            })
            setTimeout(function () {
              dialogFormVisible.value = false
            }, 900)
          }
        },
      }
  )
}


// 保存
const saveStatusToFalse = (value,render)=>{
  // console.log("v",value)
  formVisible.value = true;

  form.value.html = render;
  // console.log("r",render)
}
</script>

<style scoped>
.context {
  margin: 1% auto 0;
  width: 85%;
  background-color: white;
}

.buttonDisplay {
  position: fixed;
  right: 35px;
}
</style>